/*********************************************************************************
 *      Copyright:  (C) 2021 weizhiyan<1933283357@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  cjson.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(07/19/2021)
 *         Author:  weizhiyan <1933283357@qq.com>
 *      ChangeLog:  1, Release initial version on "07/19/2021 03:09:18 PM"
 *                 
 ********************************************************************************/


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>

#include "cjson/cJSON.h"


/* Packaged in json format */
int pack_json(char *buf,double temp,char *devid,time_t tm)
{
    if(!temp||!buf)
    {
        printf("wrong parameter!\n");
        return -1;
    }


    /* Add data to json */
    cJSON *root, *js_body, *js_list, *js_list2;
    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root,"services", js_body = cJSON_CreateArray());
    cJSON_AddItemToArray(js_body, js_list = cJSON_CreateObject());
    cJSON_AddStringToObject(js_list,"service_id","112233ww");
    cJSON_AddItemToObject(js_list,"properties",js_list2 = cJSON_CreateObject());
    cJSON_AddStringToObject(js_list2,"devID",devid);
     cJSON_AddNumberToObject(js_list2,"time",tm);
    cJSON_AddNumberToObject(js_list2,"temperature",temp);

    /* Convert to a normal string format */
    char *s = cJSON_PrintUnformatted(root);
    strcpy(buf,s);
    cJSON_Delete(root);

}

int Parse_json(char *buf, char *id, double *tem,int size_id)
{
    cJSON   *root = NULL;
    cJSON   *temp = NULL;
    char    *ptr  = NULL;
    int     len = 0;

    if(!buf||!id||!tem)
    {
        printf("buf is NULL!\n");
        return -1;
    }


    root = cJSON_Parse(buf);

    if(!root)
    {
        printf("root is NULL!\n");
        return -2;
    }

    temp = cJSON_GetObjectItem(root, "id");
    ptr = cJSON_Print(temp);
    strcpy(id, ptr);
    free(ptr);

    temp = cJSON_GetObjectItem(root, "temperature");
    ptr = cJSON_Print(temp);
    *tem = atof(ptr);
    free(ptr);

    cJSON_Delete(root);
}
